/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.utfpr.cm.tsi;

import br.edu.utfpr.cm.TSI.projetoPSA.pojos.Usuario;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Marcelo
 */
public class FiltroControladorDeAcessos implements Filter {

    private final String MENSAGEM_ERRO = "mensagemDeErro";

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (valida((HttpServletRequest) request, (HttpServletResponse) response)) {
            chain.doFilter(request, response);
        } else {
            String proximaPagina = getProximaPagina((HttpServletRequest) request);
            ((HttpServletResponse) response).sendRedirect("logon.jsp" + proximaPagina);
        }
    }

    public void destroy() {
    }

    private boolean valida(HttpServletRequest request, HttpServletResponse response) {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;

        HttpSession sessao = servletRequest.getSession();

        try {

            String acesso = new PropertiesUtils().getValorDaPropriedade(servletRequest.getRequestURI().
                    replace(servletRequest.getContextPath(), ""));

            if (acesso != null) {
                for (String string : acesso.split(",")) {
                    if ("livre".equals(string.trim())) {
                        return true;
                    }
                }
            }

            if (request.getSession().getAttribute("usuarioLogado") != null) {
                if(checarAcesso(acesso.split(","), sessao)){
                    return true;
                }else{
                    request.setAttribute(MENSAGEM_ERRO, "Acesso Negado a esta pagina!");
                    return false;
                }
            }

            return false;

        } catch (Exception e) {
            return false;
        }
    }

    private boolean checarAcesso(String[] acessos, HttpSession sessao) {
        String usuario = ((Usuario) sessao.getAttribute("usuarioLogado")).getClass().getSimpleName().trim().toUpperCase();

        for (String acesso : acessos) {
            acesso = acesso.trim().toUpperCase();
            if (acesso.equals(usuario)) {
                return true;
            }
        }
        return false;
    }

    private String getProximaPagina(HttpServletRequest httpServletRequest) {
        String next = httpServletRequest.getRequestURL().toString();
        StringBuffer params = new StringBuffer("");

        Enumeration enumParams = httpServletRequest.getParameterNames();
        while (enumParams.hasMoreElements()) {
            String name = (String) enumParams.nextElement();
            String value = httpServletRequest.getParameter(name);
            if (params.length() > 0) {
                params.append("&");
            }
            params.append(name).append("=").append(value);
        }

        return next.length() > 0 ? "?next=" + next + params : "";
    }
}
